package com.dp.mallchat.common.common.event.listener;

import com.dp.mallchat.common.common.event.UserOfflineEvent;
import com.dp.mallchat.common.user.dao.UserDao;
import com.dp.mallchat.common.user.domain.user.entity.User;
import com.dp.mallchat.common.user.domain.user.enums.UserActiveEnum;
import com.dp.mallchat.common.user.service.WebSocketService;
import com.dp.mallchat.common.user.service.adapter.WSAdapter;
import com.dp.mallchat.common.user.service.cache.UserCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @Author: dupeng
 * @CreateTime: 2024-08-08  23:15
 * @Description: 用户下线事件
 */
@Component
@Slf4j
public class UserOfflineEventListener {

    @Autowired
    private UserDao userDao;
    @Autowired
    private UserCache userCache;
    @Autowired
    private WebSocketService webSocketService;
    @Autowired
    private WSAdapter wsAdapter;

    /**
     * 更新用户下线状态
     * @param userOfflineEvent
     */
    @Async
    @EventListener(classes = UserOfflineEvent.class)
    public void userOffSave(UserOfflineEvent userOfflineEvent){
        User user = userOfflineEvent.getUser();
        user.setActiveStatus(UserActiveEnum.UN_ACTIVE.getStatus());
        userDao.updateById(user);
    }


    @Async
    @EventListener(classes = UserOfflineEvent.class)
    public void saveRedisAndPush(UserOfflineEvent event) {
        User user = event.getUser();
        userCache.offline(user.getId(), user.getLastOptTime());
        //推送给所有在线用户，该用户下线
        webSocketService.sendToAllOnlineUser(wsAdapter.buildOfflineNotifyResp(event.getUser()), event.getUser().getId());
    }

}
